package com.lhl.forum.service.impl;

import com.lhl.forum.common.AppResult;
import com.lhl.forum.common.ResultCode;
import com.lhl.forum.dao.UserMapper;
import com.lhl.forum.exception.ApplicationException;
import com.lhl.forum.model.User;
import com.lhl.forum.service.IUserService;
import com.lhl.forum.utils.MD5Util;
import com.lhl.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;


@Service
@Slf4j
public class UserServiceImp implements IUserService {

    @Resource
    private UserMapper userMapper;

    //创建用户
    @Override
    public void createNormaUser(User user) {
        //1. 非空校验
        if (user == null || StringUtil.isEmpty(user.getUsername())
                || StringUtil.isEmpty(user.getPassword()) || StringUtil.isEmpty(user.getNickname())
                || StringUtil.isEmpty(user.getSalt())) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常，统一抛出ApplicationException
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //2. 按用户名查询用户信息
        User existsuser = userMapper.selectByName(user.getUsername());
        //2.1判断用户是否存在
        if (existsuser != null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_EXISTS));
        }

        //3. 新增用户流程，设置默认值
        user.setGender((byte) 2);
        user.setArticleCount(0);
        user.setIsAdmin((byte) 0);
        user.setState((byte) 0);
        user.setDeleteState((byte) 0);

        //当前日期
        Date date = new Date();
        user.setCreateTime(date);
        user.setUpdateTime(date);

        //写入数据
        int row = userMapper.insertSelective(user);
        if (row != 1) {
            //打印日志
            log.info(ResultCode.FAILED_CREATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_CREATE.toString()));
        }

        //新增用户成功
        log.info("新增用户，username = " + user.getUsername() + ".");


    }

    //根据用户名查找用户
    @Override
    public User selectByUsername(String username) {
        //对参数进行校验
        if (StringUtil.isEmpty(username)) {
            //打印日志
            log.info(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //返回结果
        return userMapper.selectByName(username);
    }

    //用户登录
    @Override
    public User login(String username, String password) {
        //对参数进行校验
        if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password)) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));

        }

        User user = selectByUsername(username);
        //判断用户是否存在
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }

        //获取登录用户的盐
        String salt = user.getSalt();

        //根据输入的密码进行加密
        String ciphertextPassword = MD5Util.md5Salt(password, salt);

        //判断密码是否正确
        if (!ciphertextPassword.equals(user.getPassword())) {
            //打印日志
            log.warn("用户密码输入错误！");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_LOGIN));
        }

        //打印用户信息
        log.info("用户登录成功，username = " + username);

        //返回结果
        return user;
    }

    //根据id查找用户信息
    @Override
    public User selectById(Long id) {
        //非空判断
        if (id == null) {
            //打印日志
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }

        //查找用户
        User user = userMapper.selectByPrimaryKey(id);

        //返回查询结果
        return user;
    }

    //更新用户帖子1数量
    @Override
    public void addOneArticleCountById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        //根据id查询用户信息
        User user = userMapper.selectByPrimaryKey(id);
        //对查询到的版块进行非空校验
        if (user == null) {
            //打印日志
            log.warn(ResultCode.ERROR_IS_NULL.toString() + ", user id = " + id);
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_IS_NULL));
        }

        //用户帖子数量 +1
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setArticleCount(user.getArticleCount() + 1);

        int row = userMapper.updateByPrimaryKeySelective(updateUser);

        //对返回结果进行校验
        if (row != 1) {
            //打印日志
            log.warn(ResultCode.FAILED.toString() + "受影响行数不等于1");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }

    }

    @Override
    public void subOneArticleCountById(Long id) {
        //非空校验
        if (id == null || id <= 0) {
            //打印日志
            log.warn(ResultCode.FAILED_BOARD_ARTICLE_COUNT.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_BOARD_ARTICLE_COUNT));
        }

        //查找用户
        User user = userMapper.selectByPrimaryKey(id);
        //判断用户是否存在
        if (user == null) {
            //打印日志
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //判断用户状态是否正常
        if (user.getState() == 1) {
            //判断用户是否存在
            if (user == null) {
                //打印日志
                log.warn(ResultCode.FAILED_USER_BANNED.toString());
                //抛出异常
                throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_BANNED));
            }
        }


        //更新用户帖子数
        User updateUser = new User();
        updateUser.setId(id);
        updateUser.setArticleCount(user.getArticleCount() - 1);

        if (updateUser.getArticleCount() < 0){
            updateUser.setArticleCount(0);
        }

        int row = userMapper.updateByPrimaryKeySelective(updateUser);
        //判断是否更新成功
        if (row != 1){
            //打印日志
            log.warn(ResultCode.FAILED.toString() + "受影响行数不等于1");
            //抛出异常
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED));
        }


    }
}
